import ListEmptyNone from '@/components/antd-comp/empty/emptyNone'
import { useAssistantStore } from '@/store/assistantStore'
import ReactECharts from 'echarts-for-react'
import cloneDeep from 'lodash-es/cloneDeep'
import { useMemo, useRef, useState } from 'react'
import { DataBoardItemProps } from '../types'
import { exportCSVFile, getCSVTitle, multiplyAndRound } from '../utils'
import ChartContainer from './ChartContainer'
import { option } from './ChartOptions'

// 留存率
const RetentionRateChart = ({ condition, dataInfo, loading }: DataBoardItemProps) => {
  const { assistantState } = useAssistantStore()
  const eChartRef = useRef(null)
  const [chartType, setChartType] = useState('line')

  // 配置图表数据和样式
  const chartOption = useMemo(() => {
    const newOption: any = cloneDeep(option)

    // 比例设置0-100
    newOption.yAxis.min = 0
    newOption.yAxis.max = 100

    newOption.xAxis.data = dataInfo.xData
    newOption.series = [
      {
        type: chartType,
        name: '次日留存率',
        barMaxWidth: 20,
        barGap: '0%',
        data: dataInfo.nextDayRetention.map(item => multiplyAndRound(item))
      },
      {
        type: chartType,
        name: '7日留存率',
        barMaxWidth: 20,
        barGap: '0%',
        data: dataInfo.sevenDayRetention.map(item => multiplyAndRound(item))
      },
      {
        type: chartType,
        name: '15日留存率',
        barMaxWidth: 20,
        barGap: '0%',
        data: dataInfo.fifteenDayRetention.map(item => multiplyAndRound(item))
      }
    ]
    newOption.color = ['#227DFF', '#66D8E2', '#5964F3']
    newOption.grid.left = 32

    // 格式化悬浮展示内容
    newOption.tooltip.formatter = function (params) {
      const tooltipHtml = `<div>${params[0].axisValueLabel}</div>`
      const format: any[] = params.map((item: any) => `<div>${item.marker} ${item.seriesName}: ${item.value}%</div>`)
      return tooltipHtml + format.join('')
    }
    return newOption
  }, [chartType, dataInfo])

  // 所有图例都被取消选中时修复当前取消的选择
  const legendSelectChanged = params => {
    const selected = params.selected
    let allUnselected = true
    for (const name in selected) {
      if (selected[name]) {
        allUnselected = false
        break
      }
    }

    if (allUnselected && eChartRef.current) {
      eChartRef.current.getEchartsInstance().dispatchAction({
        type: 'legendSelect',
        name: params.name
      })
    }
  }

  const handleDownload = () => {
    console.log('原始数据的导出')
    const header = cloneDeep(dataInfo.xData)
    header.unshift('日期')
    const items = [
      cloneDeep(dataInfo.nextDayRetention.map(item => `${multiplyAndRound(item)}%`)),
      cloneDeep(dataInfo.sevenDayRetention.map(item => `${multiplyAndRound(item)}%`)),
      cloneDeep(dataInfo.fifteenDayRetention.map(item => `${multiplyAndRound(item)}%`))
    ]
    items[0].unshift('次日留存率')
    items[1].unshift('7日留存率')
    items[2].unshift('15日留存率')
    const title = getCSVTitle(condition, `${assistantState.name}-留存率`)
    exportCSVFile(header, items, title)
  }

  return (
    <ChartContainer
      title="留存率"
      subtitle="仅显示日维度数据"
      onChartTypeChange={type => {
        console.log('onChartTypeChange')
        setChartType(type)
      }}
      onDownload={() => {
        handleDownload()
      }}
    >
      {!loading && !dataInfo?.nextDayRetention?.length ? (
        <ListEmptyNone style={{ height: '300px' }} />
      ) : (
        <>
          {loading && (
            <div className="absolute left-0 z-10 flex h-[300px] w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
              <span className="loading loading-infinity loading-lg"></span>
            </div>
          )}
          <ReactECharts
            ref={eChartRef}
            option={chartOption}
            style={{ height: 300 }}
            notMerge
            lazyUpdate
            onEvents={{ legendselectchanged: legendSelectChanged }}
          />
        </>
      )}
    </ChartContainer>
  )
}

export default RetentionRateChart
